package com.palm.platform;

import com.palm.core.data.Item;
import com.palm.core.util.CollectionUtil;
import com.palm.core.util.castor.*;
import org.noear.solon.core.Aop;

import org.noear.solon.extend.sqltoy.DbManager;
import org.sagacity.sqltoy.dao.SqlToyLazyDao;


import javax.sql.DataSource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Config {
    static Map<String, String> configMap = new HashMap<>();
    static SqlToyLazyDao dao;
    static {
        Aop.getAsyn(DataSource.class, bw->{
            dao=DbManager.getDao(bw.get());
            loadConfig();
        });

    }
    public static void loadConfig(){
        List<Item> configItems= dao.findBySql("select code `key`,`value` title from t_config",new Item());
        configMap= CollectionUtil.toMap(configItems);
    }
    public static Long getLong(String name) {
        return LongCastor.instance.cast(configMap.get(name));
    }

    public static Boolean getBool(String name) {
        return BooleanCastor.instance.cast(configMap.get(name));
    }

    public static String getStr(String name) {
        //loadConfig();
        return StringCastor.instance.cast(configMap.get(name));
    }

    public static void saveConfig(String key,String value){
        Item item=new Item(key,value);
        dao.executeSql("update t_config set value=:title where `code`=:key",item);
        configMap.put(key,value);
    }
    public static Map<String,String> configMap(){
       // loadConfig();
        return configMap;
    }
}
